#!/bin/sh
#Copyright [2018] [jc3wish]

#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

bin_dir=
pid_file=
config_file=
dir_dir=

mode=$1    # start or stop or restart

basepath=$(cd `dirname $0`;pwd)
basepathParent=$(dirname $basepath)
__readINI () {
    INIFILE=$1; SECTION=$2; ITEM=$3;
    _readIni=`cat $INIFILE | awk 'BEGIN{FS="=";OFS=":";}/\'$SECTION'\]/,/\[.*[^('$SECTION')].*\]/{gsub(/[[:blank:]]*/,"",$1);if(NF==2 && $1=="'$ITEM'"){gsub(/^[[:blank:]]*/,"",$2);gsub(/[[:blank:]]*$/,"",$2);print $2;}}'`
    echo "${_readIni}"
}

if test -z "$bin_dir"
then
  bin_dir="$basepath"
fi

if test -z "$config_file"
then
  config_file="$basepathParent/etc/Bifrost.ini"
fi

if test -z "$dir_dir"
then
  dir_dir=$(__readINI $config_file Bifrostd data_dir);
fi

if test -z "$dir_dir"
then
  dir_dir="$basepathParent/data"
fi

if [[ $dir_dir != /* ]]; then
  dir_dir=$basepathParent"/"$dir_dir
fi

if test -z "$pid_file"
then
  pid_file=$(__readINI $config_file Bifrostd pid);
fi

if test -z "$pid_file"
then
  pid_file="$dir_dir/Bifrost.pid"
fi

case "$mode" in
  'start')
    # Start daemon
    #echo "Starting Bifrost"
    if test -x $bin_dir/Bifrost
    then
      # if in docker , remove $pid_file
      if [ -f "/.dockerenv" ];then
        rm -f $pid_file
      fi
      $bin_dir/Bifrost -d -config $config_file -pid $pid_file
    else
      echo "Couldn't find Bifrost server ($bin_dir/Bifrost)"
      exit 1
    fi
    exit 0
    ;;

  'stop')
    # Stop daemon. We use a signal here to avoid having to know the

    if test -s "$pid_file"
    then
      bifrost_pid=`cat "$pid_file"`

      if (kill -0 $bifrost_pid 2>/dev/null)
      then
        echo "Shutting down Bifrost"
        kill $bifrost_pid
        for i in 1 2 3
        do
            sleep 1
            if !(kill -0 $bifrost_pid 2>/dev/null)
            then
               echo "server stop success"
               exit 0
            fi
        done
        echo "kill $bifrost_pid failed, retry please"
        exit 1
      else
        echo "Bifrost server process #$bifrost_pid is not running!"
        rm "$pid_file"
        exit 1
      fi
      exit 0
    else
      echo "Bifrost server PID file could not be found!"
      exit 1
    fi
    ;;

  'restart')
    # Stop the service and regardless of whether it was
    # running or not, start it again.
    if ($0 stop); then
      $0 start
    else
      echo "Failed to stop running server, so refusing to try to start."
      exit 1
    fi
    ;;

  'status')
    # First, check to see if pid file exists
    if test -s "$pid_file" ; then
      bifrost_pid=`cat "$pid_file"`
      if kill -0 $bifrost_pid 2>/dev/null ; then
        echo "Bifrost running ($bifrost_pid)"
        exit 0
      else
        echo "Bifrost is not running, but PID file exists"
        exit 1
      fi
    else
      echo "PID file not exists"
      exit 1
    fi
    ;;
    *)
      # usage
      basename=`basename "$0"`
      echo "Usage: $basename  {start|stop|restart|status}  [ Bifrost server options ]"
      exit 1
    ;;
esac

exit 0
